const Koa = require('koa')
const app = new Koa()
const bodyparser = require('koa-bodyparser')
const cors=require('koa2-cors')
const routes = require('./routes/index')


//聊天模块
const { Server } = require('socket.io');
const http = require('http');
const server = http.createServer(app);
const io = new Server(server, {
    cors: {
        allowedHeaders: ["chat-room"],  // 被允许的请求头
        origin: "*",
        methods: ["GET", "POST"]
    },
});

let userList = [],socketList = {}
const {newsAdd,onlineChange}=require('./controllers/chat_controller')
io.of('my-chatroom').on('connection', (socket)=>{
    //上线操作
    socket.on("online", async (userId,online) => {
        let user = {
            id: userId,
            socket: socket.id,
        };
        userList.push(user);
        socketList[userId] = socket.id;
        onlineChange(userId,1)
        socket.emit('reonline',userId)
    })
    //发送消息
    socket.on("msg", async (data) => {
        let result=await newsAdd(data)
        //私发给某一用户
        socket.to(socketList[data.toId]).emit("getmsg",result);
    })
       //断开连接
    socket.on('disconnect', () => {
        let userId=''
        for(let item in socketList){
            if(socketList[item]=socket.id){
                userId=item
            }
        }

        socket.broadcast.emit('disonline',userId)

        onlineChange(userId,0)
    })
})
server.listen(4000, ()=>{
    console.log('socket.io服务启动')
})





const path = require('path')
// koa-static中间件，用于访问静态文件
const static = require('koa-static')
// 使用中间件，利用path模块的方法拼接出静态文件目录的绝对路径
app.use(static(path.join(__dirname,'../')))



// return '*';//设置允许来自指定域名请求

app.use(cors({
    origin: function(ctx) {
        return '*';//设置允许来自指定域名请求
    },
    maxAge: 5, //指定本次预检请求的有效期，单位为秒。
    credentials: true, //是否允许发送Cookie
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法'
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //设置服务器支持的所有头信息字段
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
}))



app.use(bodyparser({
    enableTypes:['json', 'form', 'text'],
}))


//路由
app.use(routes.routes(), routes.allowedMethods())

//启动服务器
app.listen(3000,function () {
    console.log('服务器启动了')
}
)
